//
//  QRWiFiParser.m
//  QRCodeManager
//
//  Created by Cosmin Stirbu on 4/16/13.
//  Copyright (c) 2013 Cosmin Stirbu. All rights reserved.
//

#import "QRWiFiParser.h"
#import "CoreDataManager.h"

@implementation QRWiFiParser

NSString * const SSID_REG_EX = @"S:[^;]*";
NSString * const TYPE_REG_EX = @"T:((WEP)|(WPA)|(nopass))";
NSString * const PASSWORD_REG_EX = @"P:[^;]*";

- (QRWiFi *)qrWiFi {
    NSManagedObjectContext *context = [CoreDataManager sharedInstance].managedObjectContext;
    _qrWifi = (QRWiFi *)[NSEntityDescription insertNewObjectForEntityForName:@"QRWiFi" inManagedObjectContext:context];
    _qrWifi.content = _qrData;
    if ([self parse]) {
        return _qrWifi;
    }
    // We delete it if the parsing was faulty
    [context deleteObject:_qrWifi];
    return nil;
}

- (BOOL)parse {
    // SSID
    _qrWifi.ssid = [self valueForRegEx:SSID_REG_EX withOffset:2 trimLength:0];
    
    // Type
    _qrWifi.type = [self valueForRegEx:TYPE_REG_EX withOffset:2 trimLength:0];
    
    // Password
    _qrWifi.password = [self valueForRegEx:PASSWORD_REG_EX withOffset:2 trimLength:0];
    
    return _qrWifi.ssid != nil && _qrWifi.type != nil;
}

@end
